<?php

namespace App\Http\Controllers\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\GoodsBrand;
use App\Http\Controllers\App\BaseController;

class BrandController extends BaseController
{
    /**
     * 添加商品品牌
     *
     * @param Request $request
     * @return void
     */
    public function create( Request $request )
    {
        $name = $request->input('name');
        $logo = $request->input('logo');
        $sort = (int)$request->input('sort', 1);
        $note = $request->input('note', '');

        $admin_id = session('admin_id', 0);

        GoodsBrand::create([
            'name'     => $name,
            'logo'     => $logo,
            'sort'     => $sort,
            'note'     => $note,
            'admin_id' => $admin_id,
        ]);

        return self::success('添加成功');
    }

    /**
     * 展示商品品牌
     *
     * @return void
     */
    public function show( Request $request )
    {
        $where = [];
        $name = $request->input('name');
        if ( $name ) {
            $where[] = [ 'name', '=', $name ];
        }

        $info = GoodsBrand::where($where)->paginate(15);

        return self::json( $info, '查询成功');
    }

    /**
     * 修改商品
     *
     * @param Request $request
     * @return void
     */
    public function edit( Request $request )
    {
        $id     = $request->input('id');
        $name   = $request->input('name');
        $logo   = $request->input('logo');
        $sort   = (int)$request->input('sort');
        $note   = $request->input('note');
        $status = $request->input('status');

        $admin_id = session('admin_id', 0);

        $info = GoodsBrand::find($id);

        if ( !$info) {
            return $this->error('请传递正确的品牌');
        }
        
        $info->name      =  $name;
        $info->logo      =  $logo;
        $info->sort      =  $sort;
        $info->note      =  $note;
        $info->status    =  $status;
        $info->admin_id  =  $admin_id;

        $info->save();

        return self::success('修改成功');
    }

    /**
     * 验证品牌是否存在
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function checkBrand( Request $request)
    {
      $code = $request->input('brand');

      $value = GoodsBrand::where('name', $code)->first();

      if ( $value ) {

        return self::error('品牌已存在', 10);

      } else {

        return self::success('可以添加');
        
      }
    }
}
